package com.blog.controller;

import com.blog.entity.Article;
import com.blog.security.JwtTokenProvider;
import com.blog.security.UserPrincipal;
import com.blog.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/articles")
@CrossOrigin(origins = "http://localhost:5173")
public class ArticleController {

  @Autowired
  private ArticleService articleService;

  @Autowired
  private JwtTokenProvider jwtTokenProvider;

  @PostMapping
  @PreAuthorize("hasRole('ADMIN')")
  public ResponseEntity<?> createArticle(@RequestBody Article article) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String username = authentication.getName();

    article.setAuthor(username);

    // 从SecurityContext中获取用户信息
    UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();
    Long userId = userPrincipal.getId();

    Article savedArticle = articleService.createArticle(article, userId);
    return ResponseEntity.ok(savedArticle);
  }

  @GetMapping
  public ResponseEntity<Page<Article>> getArticles(
      @RequestParam(defaultValue = "0") int page,
      @RequestParam(defaultValue = "10") int size,
      @RequestParam(required = false) String keyword,
      @RequestParam(required = false) Long categoryId,
      @RequestParam(required = false) Long tagId,
      @RequestParam(required = false) String sortBy) {

    PageRequest pageRequest;
    if (sortBy != null) {
      pageRequest = PageRequest.of(page, size, Sort.by(sortBy).descending());
    } else {
      pageRequest = PageRequest.of(page, size, Sort.by("createTime").descending());
    }

    Page<Article> articles;
    if (keyword != null && !keyword.isEmpty()) {
      articles = articleService.searchArticles(keyword, pageRequest);
    } else if (categoryId != null) {
      articles = articleService.getArticlesByCategory(categoryId, pageRequest);
    } else if (tagId != null) {
      articles = articleService.getArticlesByTag(tagId, pageRequest);
    } else {
      articles = articleService.getUserArticles(1L, pageRequest);
    }

    return ResponseEntity.ok(articles);
  }

  @GetMapping("/most-viewed")
  public ResponseEntity<Page<Article>> getMostViewedArticles(
      @RequestParam(defaultValue = "0") int page,
      @RequestParam(defaultValue = "10") int size) {
    PageRequest pageRequest = PageRequest.of(page, size);
    return ResponseEntity.ok(articleService.getMostViewedArticles(pageRequest));
  }

  @GetMapping("/most-liked")
  public ResponseEntity<Page<Article>> getMostLikedArticles(
      @RequestParam(defaultValue = "0") int page,
      @RequestParam(defaultValue = "10") int size) {
    PageRequest pageRequest = PageRequest.of(page, size);
    return ResponseEntity.ok(articleService.getMostLikedArticles(pageRequest));
  }

  @PutMapping("/{id}")
  public ResponseEntity<Article> updateArticle(@PathVariable Long id,
      @RequestBody Article article) {
    return ResponseEntity.ok(articleService.updateArticle(id, article));
  }

  @DeleteMapping("/{id}")
  public ResponseEntity<Void> deleteArticle(@PathVariable Long id) {
    articleService.deleteArticle(id);
    return ResponseEntity.ok().build();
  }

  @GetMapping("/{id}")
  public ResponseEntity<Article> getArticle(@PathVariable Long id) {
    articleService.incrementViewCount(id);
    return ResponseEntity.ok(articleService.getArticle(id));
  }

  @PostMapping("/{id}/like")
  public ResponseEntity<Void> likeArticle(@PathVariable Long id) {
    articleService.incrementLikeCount(id);
    return ResponseEntity.ok().build();
  }
}